package com.panda.admin.login.auth.service.impl;

import cn.hutool.core.util.ObjectUtil;
import com.panda.admin.login.entity.SystemUser;
import com.panda.admin.login.entity.SystemUserRole;
import com.panda.admin.login.access.service.SystemUserRoleService;
import com.panda.admin.login.auth.detailsVo.SysUserDetails;
import org.springframework.security.authentication.DisabledException;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

import javax.annotation.Resource;

/**
 * author: tcy
 * createDate: 2022/11/9
 * description:系统用户信息
 */
@Service
public class SysUserDetailServiceImpl implements UserDetailsService {

    @Resource
    private SystemUserServiceImpl systemUserService;

    @Resource
    private SystemUserRoleService systemUserRoleService;

    /**
     * 账号密码 认证
     */
    @Override
    public UserDetails loadUserByUsername(String username)  throws UsernameNotFoundException {

        SysUserDetails sysUserDetails = null;

        //查询用户存在
        SystemUser systemUser = this.systemUserService.lambdaQuery().eq(SystemUser::getAccount, username).one();

        if (ObjectUtil.isNotEmpty(systemUser)){
            //查询用户角色
            SystemUserRole userRole = systemUserRoleService.lambdaQuery().eq(SystemUserRole::getUserId, systemUser.getId()).one();
            if (ObjectUtils.isEmpty(userRole) || ObjectUtils.isEmpty(userRole.getRoleId())){
                throw new DisabledException("用户未绑定角色");
            }

            //systemUser.setPassword("{noop}" + systemUser.getPassword());
            //{bcrypt}$2a$10$hOpYisy8aBZBxdcQBLsHg.d6UJr0gU2xFAU4vqlW9Sdi10Frk1xeS
            sysUserDetails = new SysUserDetails(systemUser);
            sysUserDetails.setRoleId(userRole.getRoleId());
        }
        if (ObjectUtils.isEmpty(systemUser) || ObjectUtils.isEmpty(sysUserDetails)){
            throw new DisabledException("账号不存在");
        }
        return sysUserDetails;
    }
}
